#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/3
# @Author  : LiJun
# @Email   : lijun@tianyancha.com
# @Version : 1.0.0
import subprocess
import os


class Server_fun():

    def start_server(self, port, bport, chrome_port, device):

        for i in range(5):
            status = self.check_server(port=port)
            if status:
                break
            else:
                self.stop_server(port=port)

        cmd = f"appium --session-override --relaxed-security --local-timezone -p {port} -bp {bport} --chromedriver-port {chrome_port} " \
              f"-U {device}"
        appium = subprocess.Popen(
            cmd,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            bufsize=1,
            close_fds=True,
        )
        print("执行启动命令：{}".format(cmd))
        count = 0
        while True:
            appium_line = appium.stdout.readline().strip().decode()
            if "listener started" in appium_line or "Error: listen" in appium_line:
                print("----server_ 成功---")
                break

            count += 1
            if count > 25:
                print("启动等待时间过长")
                raise ValueError("----server_ 端口被占用，启动失败---")

    def stop_server(self, port):
        # 关闭appium server
        cmd = f"lsof -sTCP:LISTEN -i:{port} -t"
        pid = os.popen(cmd).readline().strip("\n")
        os.popen("kill -9 {}".format(pid))

    def check_server(self, port, host='127.0.0.1'):
        import socket
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        status = False
        try:
            s.connect((host, port))
            s.shutdown(2)
        except OSError as e:
            print(f'端口 {port} 没有被其他服务占用，可以使用')
            status = True
        else:
            print(f'端口 {port} 被其他服务占用了')
        return status
